<template>
  <van-dialog
    v-model="isShow"
    title="修改头像"
    show-cancel-button
    class="edit-avatar"
    @confirm="upDateImg"
    @cancel="cancel"
  >
    <div class="edit_box">
      <van-uploader
        v-model="fileList"
        :before-read="beforeRead"
        :after-read="afterRead"
        :max-count="1"
      />
    </div>
  </van-dialog>
</template>

<script>
import { Dialog, Toast } from "vant";
import { get } from "../../public/API/query.js";
import config from '../../public/config';
import Axios from 'axios'
export default {
  data() {
    return {
      fileList: [],
      condtion: {
        tx_img: ""
      },
      isShow: false,
      params: {
        photo: ""
      }
    };
  },
  methods: {
    show() {
      this.isShow = true;
      this.params.photo = this.$store.state.user.photo;
      this.fileList.push({
        url:this.$store.state.user.photo,
        isImage: true
      });
    },
    cancel() {
      this.isShow = false;
      this.fileList = [];
    },
    beforeRead(file) {
      if (
        !(
          ["jpg", "jpeg", "png", "gif"].includes(file.type.split("/")[1]) &&
          file.size < 300 * 1024
        )
      ) {
        Dialog.alert({
          title: "提示",
          message: "请上传jpg/jpeg/png/gif文件，且不超过300k！"
        });
        return false;
      }
      return true;
    },
    afterRead(file) {
      let params = new FormData();
      params.append("file", file.file);
      Axios.post(config.get('e_url')+'v1000_upload',params)
        .then(res => {
          if (res.data.code == 200) {
            this.$store.state.user.photo = res.data.data;
            this.params.photo = res.data.data;
            this.upDateImg()
          }
        })
        .catch(error => {});
    },

    upDateImg() {
      if (this.fileList.length) {
        console.log(this.params);
        get('editInfo',this.params,res=>{
          if(res.code == 200){
            Toast.success("头像修改成功！");
            this.cancel();
          }
        })
      } else {
        Toast("请先选择图片");
      }
    },
  }
};
</script>

<style lang="less">
.edit-avatar {
  .edit_box {
    text-align: center;
    padding: 0.5rem;
  }
}
</style>
